package com.hao.tool.logview.runlog.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用线程池消费日志数据
 *
 * @author sawyerlsy
 * @date 2018-12-31
 * @since
 */
@Component
public class LogConsumer {

    private ExecutorService taskExecutor = Executors.newSingleThreadExecutor();

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * websocket日志推送地址
     */
    private static final String WEBSOCKET_LOG_TOPIC = "/topic/runningLog";

    /**
     * 推送日志到 websocket可供订阅的地址中
     */
    @PostConstruct
    public void pushLogger() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        LogMessage logMessage = LogQueue.getInstance().poll();
                        if (null != logMessage) {
                            simpMessagingTemplate.convertAndSend(WEBSOCKET_LOG_TOPIC, logMessage);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        taskExecutor.submit(runnable);
    }

}
